package com.jisf.driver.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jisf.driver.entity.po.ApplicationPackage;
import com.jisf.driver.entity.po.DrivingSchoolLog;
import com.jisf.driver.entity.po.Student;
import com.jisf.driver.entity.po.StudentApply;
import com.jisf.driver.entity.vo.StudentApplyVo;
import com.jisf.driver.exception.SystemException;
import com.jisf.driver.mapper.ApplicationPackageMapper;
import com.jisf.driver.mapper.StudentApplyMapper;
import com.jisf.driver.mapper.StudentMapper;
import com.jisf.driver.mapper.UserMapper;
import com.jisf.driver.response.ResultCode;
import com.jisf.driver.service.IStudentApplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jisf.driver.utils.LogUtil;
import com.jisf.driver.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jisf
 * @since 2022-05-23
 */
@Service
public class StudentApplyServiceImpl extends ServiceImpl<StudentApplyMapper, StudentApply> implements IStudentApplyService {

    @Autowired
    private StudentApplyMapper studentApplyMapper;

    @Autowired
    private ApplicationPackageMapper applicationPackageMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LogUtil log;

    /**
     * 申请套餐
     * @param id
     * @return
     */
    @Override
    public ResultCode apply(Integer id) {
        try {
            Integer userid = UserUtil.userIdThreadLocal.get();
            StudentApply studentApply = new StudentApply();
            studentApply.setStudentId(userid);
            studentApply.setApplyId(id);
            int insert = studentApplyMapper.insert(studentApply);

            // 存储日志
            String name = applicationPackageMapper.selectById(id).getName();
            String operator = UserUtil.usernameThreadLocal.get();
            String msg = String.format("用户名为%s的用户申请套餐名为%s的套餐", operator, name);

            if (insert != 0) {
                String drivingSchoolLog = JSONObject.toJSONString(new DrivingSchoolLog(operator, msg, true));
                log.info(drivingSchoolLog);
                return ResultCode.APPLY_APPLY_SUCCESS;
            } else {
                String drivingSchoolLog = JSONObject.toJSONString(new DrivingSchoolLog(operator, msg, false));
                log.info(drivingSchoolLog);
                return ResultCode.APPLY_APPLY_FAILED;
            }
        }catch (Exception e){
            throw new SystemException(e);
        }
    }

    /**
     * 查看申请列表
     * @return
     */
    @Override
    public List<StudentApplyVo> applyList() {
        try {
            List<StudentApplyVo> studentApplyVos = studentApplyMapper.applyList();
            return studentApplyVos;
        }catch (Exception e){
            throw new SystemException(e);
        }
    }

    /**
     * 通过申请
     * @param studentApply
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultCode passApply(StudentApply studentApply) {
        try {
            Integer studentId = studentApply.getStudentId();
            Integer applyId = studentApply.getApplyId();
            ApplicationPackage applicationPackage = applicationPackageMapper.selectById(applyId);
            QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
            studentQueryWrapper.eq("userid", studentId);
            Student student = studentMapper.selectOne(studentQueryWrapper);
            student.setSubjectOneTime(student.getSubjectOneTime() + applicationPackage.getSubjectOneTime());
            student.setSubjectTwoTime(student.getSubjectTwoTime() + applicationPackage.getSubjectTwoTime());
            student.setSubjectThreeTime(student.getSubjectThreeTime() + applicationPackage.getSubjectThreeTime());
            student.setSubjectFourTime(student.getSubjectFourTime() + applicationPackage.getSubjectFourTime());
            student.setSubjectOneExam(student.getSubjectOneExam() + applicationPackage.getSubjectOneExam());
            student.setSubjectTwoExam(student.getSubjectTwoExam() + applicationPackage.getSubjectTwoExam());
            student.setSubjectThreeExam(student.getSubjectThreeExam() + applicationPackage.getSubjectThreeExam());
            student.setSubjectFourExam(student.getSubjectFourExam() + applicationPackage.getSubjectFourExam());

            int updateById = studentMapper.updateById(student);
            QueryWrapper<StudentApply> studentApplyQueryWrapper = new QueryWrapper<>();
            studentApplyQueryWrapper.eq("student_id", studentApply.getStudentId())
                    .eq("apply_id", studentApply.getApplyId());
            int delete = studentApplyMapper.delete(studentApplyQueryWrapper);

            // 存储日志
            String username = userMapper.selectById(studentId).getUsername();
            String name = applicationPackageMapper.selectById(applyId).getName();
            String operator = UserUtil.usernameThreadLocal.get();
            String msg = String.format("用户名为%s的用户通过用户名为%s的用户申请的套餐名为%s的套餐", operator, username, name);

            if (updateById != 0 || delete != 0) {
                String drivingSchoolLog = JSONObject.toJSONString(new DrivingSchoolLog(operator, msg, true));
                log.info(drivingSchoolLog);
                return ResultCode.APPLY_PASS_APPLY_SUCCESS;
            } else {
                String drivingSchoolLog = JSONObject.toJSONString(new DrivingSchoolLog(operator, msg, false));
                log.info(drivingSchoolLog);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResultCode.APPLY_PASS_APPLY_FAILED;
            }
        }catch (Exception e){
            throw new SystemException(e);
        }
    }

    /**
     * 拒绝申请
     * @param studentApply
     * @return
     */
    @Override
    public ResultCode noPassApply(StudentApply studentApply) {
        try {
            Integer studentId = studentApply.getStudentId();
            Integer applyId = studentApply.getApplyId();
            QueryWrapper<StudentApply> studentApplyQueryWrapper = new QueryWrapper<>();
            studentApplyQueryWrapper.eq("student_id", studentId)
                    .eq("apply_id", applyId);
            int delete = studentApplyMapper.delete(studentApplyQueryWrapper);

            // 存储日志
            String username = userMapper.selectById(studentId).getUsername();
            String name = applicationPackageMapper.selectById(applyId).getName();
            String operator = UserUtil.usernameThreadLocal.get();
            String msg = String.format("用户名为%s的用户拒绝用户名为%s的用户申请的套餐名为%s的套餐", operator, username, name);

            if (delete != 0) {
                String drivingSchoolLog = JSONObject.toJSONString(new DrivingSchoolLog(operator, msg, true));
                log.info(drivingSchoolLog);
                return ResultCode.APPLY_NO_PASS_APPLY_SUCCESS;
            } else {
                String drivingSchoolLog = JSONObject.toJSONString(new DrivingSchoolLog(operator, msg, false));
                log.info(drivingSchoolLog);
                return ResultCode.APPLY_NO_PASS_APPLY_FAILED;
            }
        }catch (Exception e){
            throw new SystemException(e);
        }
    }
}
